<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2018/5/28
 * Time: 下午3:50
 */

namespace App\Modules\Order\Services;


use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;
use App\Libs\Pay\WechatPay;
use App\Modules\Order\Models\Order;
use function foo\func;

class OrderService
{
    const ORDER_STATUS_UNPAID=0; #未支付
    const ORDER_STATUS_PAID=1;   #已支付
    const ORDER_STATUS_FAILED=2; #支付失败
    const ORDER_STATUS_REFUND=3; #退款
    /*const ORDER_STATUS_STR_TO_NUM_HASH = [
        'unpaid' => 0,
        'paid' =>1,
        'failed' => 2,
        'refund' => 3,
        'prepare'=>4,
        'packaged'=>5,
        'delivered'=>6,
        'received' =>7
    ];
    const ORDER_STATUS_NUM_TO_STR_HASH = [
        0 => 'unpaid',
        1 => 'paid',
        2 => 'failed',
        3 => 'refund',
        4 => 'prepare',
        5 => 'packaged',
        6 => 'delivered',
        7 => 'received'
    ];*/

    /**
     * 保存一个未支付的订单
     * @param array $data
     * @return mixed
     */
    public static function saveUnPAIDOrder($data = []) {
        $data['status'] = self::ORDER_STATUS_UNPAID;

        return Order::create($data);
    }

    /**
     * 更具ID查询
     * @param $id
     * @return mixed
     */
    public static function findById($id) {
        return Order::find($id);
    }

    /**
     * 更具订单号查询
     * @param $trade_no
     * @return mixed
     */
    public static function findByTradeNo($trade_no) {
        return Order::where('trade_no', $trade_no)->first();
    }

    /**
     * @param $pay_data
     * @return array|mixed
     */
    public static function create_unpay($pay_data) {
        $wechatPay = self::getWechatPayInstance();
        $payResultInfo = $wechatPay->send($pay_data);
        if(!$payResultInfo || count($payResultInfo) == 0){
            $payResultInfo = $wechatPay->send($pay_data);
        }
        return $payResultInfo;
    }

    /**
     * @return \App\Libs\Pay\Merchants\OfficialPay
     */
    public static function getWechatPayInstance() {
        $payConfig = array(
            'appid'=>env('WECHAT_APPID'),
            'secret'=>env('WECHAT_APP_SECRET'),
            'token'=>env('WECHAT_TOKEN'),
            'merchant_id'=>env('WECHAT_PAY_MERCHANT_ID'),
            'key'=>env('WECHAT_PAY_KEY'),
            'cert_path'=>env('WECHAT_PAY_CERT_PATH'),
            'key_path'=>env('WECHAT_PAY_KEY_PATH')
        );
        $wechatPay = WechatPay::instance($payConfig);
        return $wechatPay;
    }

    /**
     * @param $params
     * @param bool $is_all
     * @param int $page_size
     * @return mixed
     */
    public static function getOrderAndSubOrderLists($params,$is_all=false,$page_size=15) {
        $obj = Order::orderBy('id','desc');
        if(isset($params['status']) && $params['status']!='all') {
            $obj->whereExists(function ($query) use($params){
                $query->select(\DB::raw(1))
                    ->from('order_products')
                    ->whereRaw('in_orders.id = in_order_products.order_id')
                    ->where('order_products.status',$params['status']);
            });
        }
        if(isset($params['trade_no']) && $params['trade_no']) {
            $obj->where(function($query) use ($params){
                $query->whereExists(function ($query) use($params) {
                    $query->select(\DB::raw(1))
                        ->from('order_products')
                        ->whereRaw('in_orders.id = in_order_products.order_id')
                        ->where('order_products.sub_trade_no',$params['trade_no']);
                })->orwhere('trade_no',$params['trade_no']);
            });
        }
        if(isset($params['start_time'])&&$params['start_time']) {
            $obj->where('created_at','>=',$params['start_time']);
        }
        if(isset($params['end_time'])&&$params['end_time']) {
            $obj->where('created_at','<=',$params['end_time']);
        }
        if($is_all) {
            $res = $obj->get();
        }else{
            $res = $obj->paginate($page_size);
        }

        if(isset($params['status']) && $params['status']!='all') {
            foreach ($res as $key=>$each) {
                $each->order_products=$each->order_products()->where('status',$params['status'])->get();
            }
        }
        return $res;
    }

    public static function alipay_pay($trade_no,$amount,$subject="商品购买",$notify_url='') {
        $notify_url = $notify_url?$notify_url:env('ALIPAY_NOTIFY');
        Factory::setOptions(self::alipay_option($notify_url));
        $result = Factory::payment()->app()->pay($subject, $trade_no, $amount);
        //var_dump(json_encode($result));
        $res = json_decode(json_encode($result),true);
        //$body = $res['body'];
        /*$ret = explode('&',$body);
        $return_arr = [];
        foreach ($ret as $key=>&$value) {
            $value = urldecode($value);
            list($k,$v) = explode('=',$value);
            $return_arr[$k] = $v;
        }*/
        return $res;
    }

    public static function alipay_option($notify_url) {
        $options = new Config();
        $options->protocol = 'http';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->appId = env('ALIPAY_APPID');
        $options->signType = 'RSA2';
        $options->alipayPublicKey = env('ALIPAY_MCH_PUBLIC_KEY');
        $options->merchantPrivateKey = env('ALIPAY_MCH_PRIVATE_KEY');
        $options->notifyUrl = $notify_url;//"http://ysts.yax.com.cn/api/alipay_callback";

        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
        $options->encryptKey = env('ALIPAY_ENCRYPT_KEY');

        return $options;
    }
}